//
//  CategoryAddView.swift
//  KoiAccounting
//  添加类别页面
//
//  Created by 纪洪文 on 30.03.25.
//

import SwiftUI

struct CategoryAddView: View {
    @Environment(\.presentationMode) var presentationMode
    @Environment(\.presentToast) var presentToast

    @State var title: String = ""
    @State var inputCategoryName: String = ""
    @State var categoryQuery: String = ""
    @State var selectedCategoryIconType : CategoryIconType = .linearicon
    @State var selectedCategoryIcon: CategoryIcon? = nil
    @State var selectedCategoryType: CategoryType
    
    var selectedParentCategory: AccountingCategory? = nil
    var selectedCategory: AccountingCategory? = nil
    
    @StateObject var viewModel = CategoryAddViewModel()
    
    init(category: AccountingCategory) {
        self.selectedCategory = category
        self.selectedCategoryType = category.getCategoryType()
    }
    
    init(parent: AccountingCategory) {
        self.selectedParentCategory = parent
        self.selectedCategoryType = parent.getCategoryType()
    }
    
    init(selectedCategoryType: CategoryType) {
        self.selectedCategoryType = selectedCategoryType
    }
    
    public static func updateCategory(category: AccountingCategory) -> CategoryAddView {
        return CategoryAddView(category:category)
    }
    
    public static func createSub(parent: AccountingCategory) -> CategoryAddView {
        return CategoryAddView(parent:parent)
    }
    
    var body: some View {
        VStack {
            KoiToolbarView(
                title: $title,
                menuView: {
                    Button (action: {
                        saveCategory()
                    }) {
                        Text("完成")
                            .font(.system(size: 14))
                            .bold()
                            .foregroundColor(Color.koiColorPrimary)
                            .padding(.horizontal,16)
                    }
                }).padding(.top , 10)
            HStack {
                ZStack {
                    Image("koi_ic_category_grid_bg")
                        .resizable()
                        .frame(width:40, height: 40)
                    Image(getIconUri())
                        .resizable()
                        .frame(width: 24,height: 24)
                }
                .padding(.leading, 20)
                .padding(.trailing, 10)
                
                TextField("类别名称", text: $inputCategoryName)
                    .font(.system(size: 14))
                    .padding(EdgeInsets(top: 12, leading: 14, bottom: 12, trailing: 14))
                    .background(Color.koiColorBackgroundItem)
                    .cornerRadius(16)
                    .padding(.trailing, 20)
            }
            
            KoiTabBar<CategoryIconType>(selection: $selectedCategoryIconType, items: [
                TabBarItem(tab: CategoryIconType.linearicon, name: CategoryIconType.linearicon.typeName(), isLarge: true),
                TabBarItem(tab: CategoryIconType.emojiicon, name: CategoryIconType.emojiicon.typeName(), isLarge: true)
            ]).padding(.horizontal, 20)
            
            TextField("搜索类别关键词", text: $categoryQuery)
                .font(.system(size: 14))
                .padding(EdgeInsets(top: 12, leading: 14, bottom: 12, trailing: 14))
                .background(Color.koiColorBackgroundItem)
                .cornerRadius(16)
                .padding(.horizontal, 20)
                .onSubmit {
                    print("onCommit \(categoryQuery)")
                    viewModel.searchCategory(categoryQuery: categoryQuery)
                }
                .submitLabel(.search)
            TabView(selection: $selectedCategoryIconType) {
                CategoryIconSelectView(
                    selectedGroupTitle: $viewModel.linearSelectedGroupTitle,
                    groupTitles: $viewModel.linearGroupTitles,
                    selectedCategoryIconList:$viewModel.linearCategoryIconList,
                    selectedCategoryIcon:$selectedCategoryIcon,
                    searchQuery: $categoryQuery
                ).tag(CategoryIconType.linearicon)
                CategoryIconSelectView(
                    selectedGroupTitle: $viewModel.emojiSelectedGroupTitle,
                    groupTitles: $viewModel.emojiGroupTitles,
                    selectedCategoryIconList:$viewModel.emojiCategoryIconList,
                    selectedCategoryIcon:$selectedCategoryIcon,
                    searchQuery: $categoryQuery
                ).tag(CategoryIconType.emojiicon)
            }.tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
        }
        .navigationBarBackButtonHidden()
        .onChange(of: viewModel.createCategoryState) { newValue in
            if (newValue == "success") {
                presentToast(.init(message: "新增类别成功"))
                presentationMode.wrappedValue.dismiss()
            }
        }
        .onChange(of: viewModel.updateCategoryState) { newValue in
            if (newValue == "success") {
                presentToast(.init(message: "修改类别成功"))
                presentationMode.wrappedValue.dismiss()
            }
        }
        .onChange(of: selectedCategoryIcon) { newValue in
            if (selectedCategory == nil && newValue != nil) {
                inputCategoryName = newValue!.name
            }
        }
        .onAppear {
            if let category = selectedCategory {
                self.selectedCategoryType = category.getCategoryType()
                self.title = "修改类别"
                // 找图标
                selectedCategoryIconType = CategoryIcon.getCategoryIconType(iconUrl: category.icon.orEmpty)
                let iconUnified = CategoryIcon.getIconUnified(iconUrl: category.icon.orEmpty)
                let iconData = CategoryIconLocalData.findIcon(iconType: selectedCategoryIconType, iconUnified: iconUnified)
                if let temp = iconData {
                    selectedCategoryIcon = temp.icon
                    if (selectedCategoryIconType == CategoryIconType.emojiicon) {
                        viewModel.emojiSelectedGroupTitle = viewModel.emojiGroupTitles.first(where: {title in title.name == temp.name})
                        let emojiList = CategoryIconLocalData.emojiMapList.first(where: { icon in
                            icon.name == temp.name
                        })?.data
                        viewModel.emojiCategoryIconList = emojiList ?? Array()
                        viewModel.linearDefaultSelectedData()
                    } else {
                        viewModel.linearSelectedGroupTitle = viewModel.linearGroupTitles.first(where: { title in title.name == temp.name})
                        let linearList = CategoryIconLocalData.linearMapList.first(where: { icon in
                            icon.name == temp.name
                        })?.data
                        viewModel.linearCategoryIconList = linearList ?? Array()
                        viewModel.emojiDefaultSelectedData()
                    }
                }
                self.inputCategoryName = category.name.orEmpty
            } else {
                viewModel.linearDefaultSelectedData()
                viewModel.emojiDefaultSelectedData()
                if (selectedParentCategory != nil) {
                    self.title = getTitle(sub:"二级")
                } else {
                    self.title = getTitle()
                }
            }
        }
    }
    
    private func getTitle(sub:String = "") -> String {
        if (selectedCategoryType == .income) {
            return "新增收入\(sub)类别"
        } else {
            return "新增支出\(sub)类别"
        }
    }
    
    private func getIconUri() -> String {
        if (selectedCategoryIcon == nil) {
            return "koi_ic_question"
        } else {
            return selectedCategoryIcon!.getIconAsset()
        }
    }
    
    private func saveCategory() {
        // 如果没有输入类别名称
        if (inputCategoryName.isEmpty) {
            presentToast(.init(message: "请输入类别名称"))
            return
        }
        if (selectedCategoryIcon == nil) {
            presentToast(.init(message: "请选择类别图标"))
            return
        }
        // 新增或者更新
        if (selectedCategory != nil) {
            viewModel.updateCategory(
                category: selectedCategory,
                name: inputCategoryName,
                icon: selectedCategoryIcon!.getIconUri()
            )
        } else {
            viewModel.saveCategory(
                name:inputCategoryName,
                icon:selectedCategoryIcon!.getIconUri(),
                type: selectedCategoryType.rawValue,
                parentId: selectedParentCategory?.cid
            )
        }
    }
}

struct CategoryGroupTitleView : View {
    
    var title: CategoryGroupTitle
    var selectedTitleName: String
    
    var body: some View {
        Text(title.name)
            .font(.system(size: 14))
            .foregroundColor(selectedTitleName == title.name ? Color.white : Color.koiColorTitle)
            .bold()
            .padding(EdgeInsets(top: 6, leading: 14, bottom: 6, trailing: 14))
            .background(selectedTitleName == title.name ? Color.koiColorPrimary : Color.koiColorBackgroundItem)
            .cornerRadius(46)
    }
}

#Preview {
    CategoryAddView(category: AccountingCategory(name:"餐饮"))
}
